#!/bin/env python
# -*- coding: utf-8 -*-
import wx
import os
import socket
import time
import threading


def recv_timeout(the_socket, timeout=2):
    the_socket.setblocking(0)
    total_data = []
    data = ""
    begin = time.time()
    while 1:
        if total_data and time.time() - begin > timeout:
            break
        elif time.time() - begin > timeout * 2:
            break

        try:
            data = the_socket.recv(1024)
            if data:
                total_data.append(data)
                begin = time.time()
            else:
                time.sleep(0.1)
        except:
            pass

    the_socket.setblocking(1)
    return ''.join(total_data)


class OpenDialog(wx.Dialog):

    def __init__(self):
        super(OpenDialog, self).__init__(None, -1, "Open Remote File",
                                         style=wx.DEFAULT_DIALOG_STYLE | wx.CLOSE_BOX | wx.MINIMIZE_BOX)

        okButton = wx.Button(self, wx.ID_OK, "OK", pos=(15, 15))
        okButton.SetDefault()
        cancelButton = wx.Button(self, wx.ID_CANCEL, "Cancel", pos=(115, 15))
        self.InitUI()
        self.SetSize((400, 300))
        self.Center()

    def InitUI(self):
        pass


class MainWindow(wx.Frame):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.TitleName = "Simple Editor"
        self.current_file = ""

        self.InitUI()
        self.ConnectHost()

        self.SetSize((800, 600))
        self.SetTitle(self.TitleName)
        self.Center()
        self.Show()

    def InitUI(self):

        menubar = wx.MenuBar()
        self.statusBar = self.CreateStatusBar()
        fileMenu = wx.Menu()
        fopen = fileMenu.Append(wx.ID_OPEN, 'Open', "Open File")
        fquit = fileMenu.Append(wx.ID_EXIT, 'Quit', 'Quit application')

        editMenu = wx.Menu()
        copy = editMenu.Append(wx.ID_COPY, 'Copy', "Copy")
        cut = editMenu.Append(wx.ID_CUT, 'Cut', "Cut")
        paste = editMenu.Append(wx.ID_PASTE, 'Paste', "Paste")
        helpMenu = wx.Menu()

        menubar.Append(fileMenu, '&File')
        menubar.Append(editMenu, '&Edit')
        menubar.Append(helpMenu, '&Help')
        self.SetMenuBar(menubar)

        self.Bind(wx.EVT_MENU, self.OnQuit, fquit)
        self.Bind(wx.EVT_MENU, self.OnOpen, fopen)

        panel = wx.Panel(self, -1)
        panel.SetBackgroundColour("white")
        vbox = wx.BoxSizer(wx.VERTICAL)

        self.midText = wx.TextCtrl(
            panel, style=wx.TE_MULTILINE | wx.HSCROLL | wx.TE_READONLY)
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        editButton = wx.Button(panel, label="编辑", size=(50, 30))
        uploadButton = wx.Button(panel, label="上传", size=(50, 30))
        self.Bind(wx.EVT_BUTTON, self.OnEdit, editButton)
        hbox.Add(editButton, border=10)
        hbox.Add(uploadButton, border=10)

        vbox.Add(hbox, border=10)
        vbox.Add(self.midText, 1, wx.EXPAND | wx.ALL, 10)
        panel.SetSizer(vbox)

    def OnQuit(self, e):
        self.Close()

    def OnOpen(self, e):

        current_path = os.sep
        self.cmdport.send("ls {}\n".format(current_path))
        fls = eval(recv_timeout(self.cmdport))
        while True:

            dlg = wx.SingleChoiceDialog(None,  u"current path:{}".format(current_path),
                                        "Choose file", fls)
            dlg.Center()

            if dlg.ShowModal() == wx.ID_OK:
                current_path = u"{}{}{}".format(current_path,dlg.GetStringSelection(),os.sep)
                self.cmdport.send(u"ls {}\n".format(current_path).encode("utf-8"))
                fls = eval(recv_timeout(self.cmdport))
                if not isinstance(fls, list):
                    self.dataReady = True
                    self.transferfile = fls
                    break
            else:
                break
        self.midText.SetEditable(False)
        dlg.Destroy()
# dialog = wx.FileDialog(
#     None, "Choose a file", os.getcwd(), "", "*.txt", wx.OPEN)
# if dialog.ShowModal() == wx.ID_OK:
#     self.midText.SetValue(open(dialog.GetPath()).read())

    def OnEdit(self, e):
        self.midText.SetEditable(True)
        self.SetTitle("{} : Edit {}".format(self.TitleName, self.current_file))

    def ConnectHost(self):
        self.host = "127.0.0.1"
        self.dport = 1234
        self.transferfile = ""
        self.cmdport = socket.socket()
        try:
            self.cmdport.connect((self.host, self.dport))
            self.statusBar.SetStatusText(self.cmdport.recv(1024))
            self.cmdport.send("cmd port\n")
        except:
            self.statusBar.SetStatusText("connect error")

        self.dataReady = False
        self.datathread = threading.Thread(target=self.HandleData)
        self.datathread.start()

    def HandleData(self):
        self.datasocket = socket.socket()
        self.datasocket.connect((self.host, self.dport))
        self.datasocket.send(
            "data {:d}\n".format(self.cmdport.getsockname()[1]))
        self.datasocket.recv(1024)
        while True:
            if self.dataReady:
                self.datasocket.send("request {}\n".format(self.transferfile))
                contents = recv_timeout(self.datasocket)
                print contents
                self.midText.SetValue(contents)
                self.dataReady = False

        self.datasocket.close()

    def OnExit(self):
        self.datasocket.close()
        self.cmdport.close()


def main():

    ex = wx.App()
    MyFrame = MainWindow(
        None, style=wx.DEFAULT_FRAME_STYLE ^ (
            wx.MAXIMIZE_BOX |
            wx.RESIZE_BORDER))
    ex.SetTopWindow(MyFrame)
    ex.MainLoop()

if __name__ == "__main__":
    main()
